package com.example.vw.tabletest.fragment;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;

import com.example.vw.tabletest.R;
import com.example.vw.tabletest.bean.ReportInfo;
import com.example.vw.tabletest.util.Constant;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ExcelsPagerFragmentLocalJS extends Fragment {

    private WebView mWebTable;
    private ProgressDialog mLoadTabledialog;//加载表格时的进度框
    private WebViewClient refreshTableClient;//携带样式和数据进行页面刷新的WebViewClient
    private Button mBtRefresh; // 刷新测试按钮
    private ReportInfo mReport;

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //表格数据的准备，以及网页表格的绘制
        new InitTableTask().execute();

        mLoadTabledialog = new ProgressDialog(getActivity());
        mLoadTabledialog.setMessage("正在加载表格...");
        mLoadTabledialog.setIndeterminate(true);
        mLoadTabledialog.setCancelable(false);
        mLoadTabledialog.show();
    }

    private void loadTableRefresh(final String tableId){
        Toast.makeText(this.getContext(), tableId,Toast.LENGTH_SHORT).show();
        mWebTable.post(new Runnable() {
            @Override
            public void run() {
                mWebTable.setWebViewClient(refreshTableClient);
            }
        });
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //获得传递的参数
        Bundle arguments = getArguments();
        mReport = new ReportInfo();
        mReport.setId(arguments.getString(Constant.KEY_ID));
        mReport.setText(arguments.getString(Constant.KEY_TEXT));
        mReport.setUrl(arguments.getString(Constant.KEY_URL));

        refreshTableClient = new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
//                mWebTable.loadUrl(url);
//                view.evaluateJavascript("javascript:load('1538235454853', '510122106200001', 2018, 4, '278_1')",null);
            }
        };
    }



    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_excel, null);
        /*mBtRefresh = (Button) view.findViewById(R.id.bt_refresh);
        mBtRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mWebTable.evaluateJavascript("javascript:load('1538235454853', '510122106200001', 2018, 4, '278_1')",null);
            }
        });*/
        mWebTable = (WebView) view.findViewById(R.id.web_table);

        try {
            //webView初始化
            WebSettings webSettings = mWebTable.getSettings();
            webSettings.setJavaScriptEnabled(true);
            webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
            webSettings.setAllowContentAccess(true);
            webSettings.setAppCacheEnabled(true);
            webSettings.setUseWideViewPort(true);
            webSettings.setDomStorageEnabled(true);
//            webSettings.setDatabaseEnabled(true);
//            webSettings.setAppCacheEnabled(true);
            webSettings.setLoadWithOverviewMode(true);
            webSettings.setSupportZoom(true);
            webSettings.setBuiltInZoomControls(true);
            webSettings.setDisplayZoomControls(false);
            webSettings.setLoadsImagesAutomatically(true);//自动加载图片
            webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
            webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
            webSettings.setDefaultTextEncodingName("utf-8");
            webSettings.setSupportMultipleWindows(true);
            webSettings.setAllowUniversalAccessFromFileURLs(true);
            mWebTable.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
            mWebTable.setHorizontalScrollBarEnabled(true);
            mWebTable.setInitialScale(100);

            /*WebSettings settings = mWebTable.getSettings();
            settings.setDisplayZoomControls(false); //隐藏webview缩放按钮
            //支持javascript
            settings.setJavaScriptEnabled(true);
            // 设置可以支持缩放
            settings.setSupportZoom(false);
            // 设置出现缩放工具
            settings.setBuiltInZoomControls(false);
            //扩大比例的缩放
            settings.setUseWideViewPort(true);
            settings.setDomStorageEnabled(true);
            settings.setDatabaseEnabled(true);
            settings.setAppCacheEnabled(true);
            //自适应屏幕
            settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
            settings.setDefaultTextEncodingName("utf-8");
            settings.setLoadWithOverviewMode(true);
            settings.setNeedInitialFocus(true);
            settings.setLoadsImagesAutomatically(true);//自动加载图片
            settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
            settings.setSupportMultipleWindows(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);

            mWebTable.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
            mWebTable.setHorizontalScrollBarEnabled(true);
            mWebTable.setInitialScale(100);*/


            try {
                if (Build.VERSION.SDK_INT >= 16) {
                    Class<?> clazz = mWebTable.getSettings().getClass();
                    Method method = clazz.getMethod(
                            "setAllowUniversalAccessFromFileURLs", boolean.class);
                    if (method != null) {
                        method.invoke(mWebTable.getSettings(), true);
                    }
                }
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }

            mWebTable.clearCache(true);
            // 设置js和Android的交互
//            mWebTable.addJavascriptInterface(this, "excel");
//            String urlFormat = "http//211.103.218.91.8095/appdemo.html?table={1}&year={2}&period={3}&userID={4}";
//            String url = "http://211.103.218.91:8095/appdemo.html?table=1538235454853&catalogID=510122106200001&year=2018&period=4&userID=278_1";
            String url = "https://cn.bing.com/search?q=%E6%AD%BB%E7%A5%9E&qs=n&form=QBLH&sp=-1&pq=%E6%AD%BB%E7%A5%9E&sc=8-2&sk=&cvid=5A819FF69CE84CD49848F60DEE556EF4";
//            String url = String.format(urlFormat,15)
//            String url = "file:///android_asset/tj_new/appdemo.html";
            mWebTable.loadUrl(mReport.getUrl());
//            loadTableRefresh("测试");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return view;
    }


    /**
     * 用于后台读取excel文件并绘制网页的异步线程
     */
    private class InitTableTask extends AsyncTask<String, Integer, String> {

        @Override
        protected String doInBackground(String... params) {
            return null;
        }

        @Override
        protected void onPostExecute(final String data) {
//            String url = "file:///android_asset/tj_new/appdemo.html";
//            mWebTable.loadUrl(url);
            loadTableRefresh("测试");
            //停止加载dialog
            if (mLoadTabledialog.isShowing()) {
                mLoadTabledialog.dismiss();
            }
        }
    }

}
